#include <iostream>
#include <curl/curl.h>
#include <nlohmann/json.hpp>
#include <fstream>
#include <stdlib.h>
#include <regex>
#include <string>
#include <cstring>
#include <unistd.h>
#include "curl.cpp"
#include "sqlite3.cpp"

using namespace std;
using json=nlohmann::json;

void add(string ret)
{
	json r=json::parse(ret);
	string sql="select * from ipc where query='"+(string)r["query"]+"';";
	string res=sqlite3_select(sql);
	json result=json::parse(res);
	if(result.size()==0)
	{ 	
		sql="insert into ipc (country,countryCode,region,regionName,city,lat,lon,timezone,isp,\
		org,asd,query,status)values('" +(string)r["country"]+ "','" +(string)r["countryCode"]+ "','" 
		+(string)r["region"]+ "','" +(string)r["regionName"]+ "','" +(string)r["city"]+ "','" 
		+to_string(r["lat"])+ "','" +to_string(r["lon"])+ "','" +(string)r["timezone"]+ "','" 
		+(string)r["isp"]+ "','" +(string)r["org"]+ "','" +(string)r["as"]+ "','" +(string)r["query"]+ "','" 
		+(string)r["status"]+ "');";
		sqlite3_idu(sql);
	}
}

string ipaddr(string ip)
{
	string ips="http://ip-api.com/json/"+ip;
	const char* url=ips.c_str();
	string r=curl2(url);
	add(r);
	return r;
}

string listindex()
{
	string sql="select * from ipc order by id desc limit 0,10;";
	string res=sqlite3_select(sql);
	return res;
}

string glimit(int p)
{
	string sql="select * from ipc order by id asc limit "+to_string(p*2)+",10;";
	string res=sqlite3_select(sql);
	return res;
}

string gpage()
{
	string sql="select count(*) from ipc;";
	string res=sqlite3_select(sql);
	json r=json::parse(res);
	string page=r[0][0];
	return page;
}

//query
string gsearchpage(string key)
{
	string sql="select count(*) from ipc where query LIKE '%"+key+"%\';";
	string res=sqlite3_select(sql);
	json r=json::parse(res);
	string page=r[0][0];
	return page;
}

string gsearch(string key)
{
	string sql="select * from ipc where query LIKE '%"+key+"%\' order by id asc limit 0,10;";
	string res=sqlite3_select(sql);
	return res;
}

string gsearchlimit(int p,string key)
{
	string sql="select * from ipc where query LIKE '%"+key+"%\' order by id asc limit "+to_string(p*2)+",10;";
	string res=sqlite3_select(sql);
	return res;
}

